package config

import (
	"bytes"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"time"
)

func Log() gin.HandlerFunc {
	return func(c *gin.Context) {

		logger := zap.NewExample()

		// 记录请求时间
		start := time.Now()

		// 使用自定义 ResponseWriter
		crw := &CustomResponseWriter{
			body:           bytes.NewBufferString(""),
			ResponseWriter: c.Writer,
		}
		c.Writer = crw

		// 打印请求信息
		reqBody, _ := c.GetRawData()

		//logger.InfoContext(c, "wjlog", logger.String("c.Request.Method", c.Request.Method),
		//	logger.String("c.Request.RequestURI", c.Request.RequestURI),
		//	logger.String("reqBody", string(reqBody)))

		logger.Info("wjlog", zap.String("c.Request.Method", c.Request.Method),
			zap.String("c.Request.RequestURI", c.Request.RequestURI),
			zap.String("reqBody", string(reqBody)))

		// 执行请求处理程序和其他中间件函数
		c.Next()

		// 记录回包内容和处理时间
		end := time.Now()
		latency := end.Sub(start)
		respBody := string(crw.body.Bytes())

		//logger.InfoContext(c, "wjlog", logger.String("c.Request.Method", c.Request.Method),
		//	logger.String("c.Request.RequestURI", c.Request.RequestURI),
		//	logger.String("respBody", respBody),
		//	logger.Int("latency", int(latency)),

		logger.Info("wjlog",
			zap.String("c.Request.Method", c.Request.Method),
			zap.String("c.Request.RequestURI", c.Request.RequestURI),
			zap.String("respBody", respBody),
			zap.Int("latency", int(latency)),
		)

	}
}

// CustomResponseWriter 封装 gin ResponseWriter 用于获取回包内容。
type CustomResponseWriter struct {
	gin.ResponseWriter
	body *bytes.Buffer
}

func (w CustomResponseWriter) Write(b []byte) (int, error) {
	w.body.Write(b)
	return w.ResponseWriter.Write(b)
}
